package com.asggo.g21.listener;

import cn.hutool.core.collection.CollUtil;
import com.asggo.g21.holder.SseEmitterHolder;
import com.asggo.g21.utils.SseEmitterUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2024/3/27 18:01
 */
@Slf4j
public class SseTopicListener implements ApplicationRunner, Ordered {

  @Override
  public void run(ApplicationArguments args) throws Exception {
    SseEmitterUtil.subscribeMessage(message -> {
      log.info("SSE 主题订阅收到消息session keys={} message={}", message.getSessionKeys(),
          message.getMessage());
      // 如果key不为空就按照key发消息 如果为空就群发
      if (CollUtil.isNotEmpty(message.getSessionKeys())) {
        message.getSessionKeys().forEach(key -> {
          if (SseEmitterHolder.existSession(key)) {
            SseEmitterUtil.sendMessage(key, message.getMessage());
          }
        });
      } else {
        SseEmitterHolder.getAllSessionKeys().forEach(key
            -> SseEmitterUtil.sendMessage(key, message.getMessage()));
      }
    });
    log.info("初始化SSE主题订阅监听器成功");
  }

  @Override
  public int getOrder() {
    return 0;
  }
}
